package com.cnswhy.cloud.server.iot.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.cnswhy.cloud.common.core.base.boot.BaseConfig;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableConfigurationProperties(WxProperties.class)
public class CnswhyServerAppResourceServerConfigure  extends BaseConfig implements WebMvcConfigurer {

    @Bean
    public CnswhyAppInteceptorConfigure cnswhyAppInteceptorConfigure() {
        return new CnswhyAppInteceptorConfigure();
    }

    @Autowired
    WxProperties wxProperties;

    private static WxMaService wxMaService = null;

    @Bean
    public Object wxMaService() {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
        config.setAppid(wxProperties.getAppid());
        config.setSecret(wxProperties.getSecret());
        config.setToken(wxProperties.getToken());
        config.setAesKey(wxProperties.getAesKey());
        config.setMsgDataFormat(wxProperties.getMsgDataFormat());
        //config.setToken(token);
        //config.setAesKey(aesKey);

        wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(config);

        return Boolean.TRUE;
    }

    public static WxMaService getWxMaService() {
        return wxMaService;
    }

    @Bean
    @ConditionalOnMissingBean
    public WxPayService wxService() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(wxProperties.getAppPayId()));
        payConfig.setMchId(StringUtils.trimToNull(wxProperties.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(wxProperties.getMchKey()));
        payConfig.setSignType("MD5");
        payConfig.setNotifyUrl(StringUtils.trimToNull(wxProperties.getNotifyUrl()));
        // payConfig.setKeyPath(StringUtils.trimToNull(wxPayProperties.getKeyPath()));

        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
}
